package com.fkdx.service;

import com.alibaba.fastjson.JSON;
import com.fkdx.common.dto.sys.CurrentUserDTO;
import com.fkdx.common.enums.SysStatusEnum;
import com.fkdx.common.sys.SecurityHelper;
import com.fkdx.dao.condition.TaskCondition;
import com.fkdx.dao.entity.PageResult;
import com.fkdx.dao.entity.Task;
import com.fkdx.dao.entity.Tical;
import com.fkdx.dao.entity.User;
import com.fkdx.dao.mapper.TaskMapper;
import com.fkdx.dao.mapper.TicalMapper;
import com.fkdx.dao.mapper.UserMapper;
import com.fkdx.service.dto.*;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author: create by wsh
 * @date:2022/8/20
 */
@Log4j2
@Service()
public class TaskService {

  @Resource
  private TaskMapper taskMapper;
  @Resource
  private TicalMapper ticalMapper;
  @Resource
  private UserMapper userMapper;
  @Resource
  private DictService dictService;

  /**
   * 获取粮食品种集合     *     * @param req     * @return
   */
  public PageResult<TaskQueryResp> getTaskList(TaskQueryReq req) {
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    TaskCondition condition = new TaskCondition();
    BeanUtils.copyProperties(req, condition);
    condition.setTenantId(principal.getTenantId());
    List<Task> list = taskMapper.selectAll(condition);
    PageResult<TaskQueryResp> results = new PageResult<>(list, (m) -> {
      TaskQueryResp res = new TaskQueryResp();
      BeanUtils.copyProperties(m, res);
      return res;
    });
    return results;
  }

  /**
   * 获取详情     *     * @param id     * @return
   */
  public TaskQueryResp getTaskForm(Long id) {
    TaskQueryResp resp = new TaskQueryResp();
    Task task = taskMapper.selectByPrimaryKey(id);
    BeanUtils.copyProperties(task, resp);
    return resp;
  }

  /**
   * 新增、修改     *     * @param req
   */
  public void saveTaskForm(TaskReq req) {
    Task task = new Task();
    BeanUtils.copyProperties(req, task);
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    Date d = new Date();
    if (req.getId() == null) {
      task.setName(principal.getName());
      task.setCreated(d);
      task.setModified(d);
      //完成
      if (task.getStatus() == null) {
        task.setStatus(2);
      }
      task.setCreateUserId(principal.getId());
      task.setCreateUserName(principal.getName());
      task.setModificationUserId(principal.getId());
      task.setModificationUserName(principal.getName());
      task.setTenantId(principal.getTenantId());
      task.setYn(SysStatusEnum.YES.getStatus());
      taskMapper.insert(task);
    } else {
      task.setModificationUserId(principal.getId());
      task.setModificationUserName(principal.getName());
      taskMapper.updateByPrimaryKey(task);
    }
  }

  /**
   * 删除     *     * @param id
   */
  public void removeTaskList(Long[] id) {
    taskMapper.updateByIds(Lists.newArrayList(id));
  }

  public Task getTaskStatus(Task r) {
    return taskMapper.selectStatus(r);
  }

  @Transactional(rollbackFor = RuntimeException.class)
  public void addTaskForm(TaskReq req) {
    Task task = new Task();
    BeanUtils.copyProperties(req, task);
    Date d = new Date();
    if (req.getId() == null) {
      task.setCreated(d);
      task.setModified(d);
      //完成
      if (task.getStatus() == null) {
        task.setStatus(2);
      }
      task.setModificationUserId(0L);
      task.setModificationUserName("system");
      task.setYn(SysStatusEnum.YES.getStatus());
      taskMapper.insert(task);
    } else {
      Task t = taskMapper.selectByPrimaryKey(req.getId());
      if (t != null) {
        log.info("请求修改日志{}", JSON.toJSONString(req));
        if (req.getStatus() == 0) {
          task.setModificationUserId(0L);
          task.setModificationUserName("system");
          taskMapper.updateSelective(task);
        } else if (req.getStatus() == 2) {
          task.setModificationUserId(0L);
          task.setModificationUserName("system");
          taskMapper.updateSelective(task);
        } else if (req.getStatus() == 4) {
          taskMapper.updateByPid(t.getPid());
          Tical record = new Tical();
          record.setId(t.getPid());
          record.setResult(req.getResult());
          record.setStatus(3);
          record.setBalance(req.getBalance());
          ticalMapper.updateSelective(record);
        } else if (req.getStatus() == 3) {
          task.setStatus(0);
          task.setModificationUserId(0L);
          task.setModificationUserName("system");
          task.setBalance(req.getBalance());
          taskMapper.updateSelective(task);
        } else {
          task.setModificationUserId(0L);
          task.setModificationUserName("system");
          task.setBalance(req.getBalance());
          taskMapper.updateSelective(task);
          Task r = new Task();
          r.setPid(t.getPid());
          r.setStatus(1);
          List<Task> list = taskMapper.selectByPid(r);
          StringBuilder s = new StringBuilder();
          for (Task a : list) {
            s.append(a.getResult()).append("\n");
          }
          Tical c = ticalMapper.selectByPrimaryKey(t.getPid());
          Tical record = new Tical();
          record.setId(t.getPid());
          record.setResult(s.toString());
          if (c.getNum() == list.size()) {
            record.setStatus(1);
          } else {
            record.setStatus(0);
          }
          record.setBalance(req.getBalance());
          ticalMapper.updateSelective(record);

          User user = userMapper.selecUserByUserName(t.getName());
          DictQueryResp dict = dictService.getDictCode(t.getType().toString());
          Integer val = Integer.parseInt(dict.getDataCode());
          User u = new User();
          u.setId(user.getId());
          u.setIntegral(user.getIntegral() - val);
          userMapper.updateSelective(u);
        }
      }
    }
  }

  public void saveBatch(Tical t) {
    Date d = new Date();
    CurrentUserDTO principal = SecurityHelper.getPrincipal();
    List<Task> arr = new ArrayList<>();
    for (int i = 0; i < t.getNum(); i++) {
      Task task = new Task();
      BeanUtils.copyProperties(t, task);
      task.setStatus(2);
      task.setId(null);
      task.setPid(t.getId());
      task.setResult(null);
      task.setCreateUserId(principal.getId());
      task.setCreateUserName(principal.getName());
      task.setModificationUserId(principal.getId());
      task.setModificationUserName(principal.getName());
      task.setTenantId(principal.getTenantId());
      task.setYn(SysStatusEnum.YES.getStatus());
      arr.add(task);
    }
    taskMapper.insertBatch(arr);
  }

  public List<TaskDownResp> downloadList(String ids) {
    List<Long> pids = new ArrayList<>();
    String[] str = ids.split(",");
    for (String s :str) {
      pids.add(Long.parseLong(s));
    }
    List<Task> list = taskMapper.selectByPids(pids);
    List<TaskDownResp> results = new ArrayList<>();
    list.forEach(m ->{
      TaskDownResp r = new TaskDownResp();
      r.setUrl(m.getUrl());
      r.setPrice(m.getPrice());
      r.setResult(m.getResult());
      results.add(r);
    });
    return results;
  }

  public Integer getTaskCount(Long pid) {
    return taskMapper.selectTaskCount(pid);
  }
}
